﻿using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Batman.Cms.Controllers.Inputs;
using Batman.Cms.Controllers.Pages.Dto;
using Batman.Cms.Core.Services;
using Batman.Cms.Core.Tools;
using Batman.Cms.Domains;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Batman.Cms.Services
{
    public class ArticleAppSvc : ServiceBase<Article>
    {
        public ArticleAppSvc(IRepository<Article> repository, ToolBox toolBox) : base(repository, toolBox)
        {
        }

        public void Create(CreateArticleInput model)
        {
            var entity = ObjectMapper.Map<Article>(model);

            Repository.Insert(entity);
        }

        public void Update(UpdateArticleInput model)
        {
            var record = Repository.GetAll().AsNoTracking().FirstOrDefault(t => t.Id == model.Id);
            var entity = ObjectMapper.Map<Article>(model);

            // 统计不变
            entity.Counter = record.Counter;

            Repository.Update(entity);
        }

        public PagedResultDto<Article> GetArticles(PagedResultRequestDto page)
        {
            var query = Repository.GetAll().AsNoTracking();
            var total = query.Count();

            var data = query.OrderByDescending(t => t.Id).ToList();

            return new PagedResultDto<Article>(total, data);
        }

        public ArticleDisplayDto GetArticleForDisplay(int id)
        {
            var artile = Get<ArticleDisplayDto>(id);
            if (artile == null) throw new Exception("404");

            var info = Query<Article>("get-article-preve-next-info", new { id });
            var prev = info.FirstOrDefault(t => t.Id < id);
            if (prev != null)
            {
                artile.PrevId = prev.Id;
                artile.PrevTitle = prev.Title;
            }
            var next = info.FirstOrDefault(t => t.Id > id);
            if (next != null)
            {
                artile.NextId = next.Id;
                artile.NextTitle = next.Title;
            }
            return artile;
        }
    }
}
